let selectedImage = null;

// 获取存储的评论
function loadComments() {
    const comments = JSON.parse(localStorage.getItem('comments')) || [];
    comments.forEach(comment => addCommentToDOM(comment.text, comment.image, comment.time));
}

// 优化创建评论元素的函数
function addCommentToDOM(text, image, time) {
    const comments = document.getElementById('comments');
    const commentDiv = document.createElement('div');
    commentDiv.className = 'comment';
    
    const content = `
        <img src="${image}" alt="selected">
        <div>
            <p>${text}</p>
            <p>${time}</p>
        </div>
        <span class="delete-button" onclick="deleteComment(this)">删除</span>
    `;

    commentDiv.innerHTML = content;
    comments.appendChild(commentDiv);
}

// 加载评论
loadComments();

function selectImage(imgElement) {
    document.querySelectorAll('.image').forEach(img => img.classList.remove('selected'));
    imgElement.classList.add('selected');
    selectedImage = imgElement.src;
}

function updateCharacterCount() {
    const commentBox = document.getElementById('comment');
    const remaining = 180 - commentBox.value.length;
    document.getElementById('charCount').textContent = `还可以输入${remaining}个字符,最多180个`;
}

function submitComment() {
    const commentBox = document.getElementById('comment');
    if (!selectedImage || commentBox.value.length === 0) {
        alert('请先选择图片并输入内容！');
        return;
    }

    const commentText = commentBox.value;
    const time = new Date().toLocaleString();
    
    // 将评论存储到 localStorage
    const comments = JSON.parse(localStorage.getItem('comments')) || [];
    comments.push({ text: commentText, image: selectedImage, time: time });
    localStorage.setItem('comments', JSON.stringify(comments));

    // 更新 UI
    addCommentToDOM(commentText, selectedImage, time);

    commentBox.value = '';
    updateCharacterCount();
}

function deleteComment(deleteBtn) {
    const comment = deleteBtn.parentElement;
    const commentText = comment.children[1].children[0].textContent; // 获取评论文本
    const storedComments = JSON.parse(localStorage.getItem('comments')) || [];

    // 过滤掉被删除的评论
    const updatedComments = storedComments.filter(c => c.text !== commentText);
    localStorage.setItem('comments', JSON.stringify(updatedComments));

    comment.remove();
}
